<?php
	
	// TODO complete this doc
	/**
	 * This function calculate a password hash using a provided password and
	 * an random extra text.
	 * If no extra text is provided, function generates a random one.
	 * This extra text must be a hexadecimal string of eight characters lenght.
	 * Function takes the extra text, if provided, or generate a new one,
	 * then concatenate it with the password and use md5 again to create a 32
	 * characters hash. Then concatenate again the extra text with the hash (to
	 * keep it for further reference) and returns that result.
	 *  
	 * @param string $password
	 * @param string $additionalText
	 * 
	 * @return string
	 */
	function calculatePasswordHash ($password, $xtraText = null) {

		// generate random extra text if not provided
		if ($xtraText == null) {
			$xtraText = substr(md5(uniqid(rand(), true)), 0, 8);
		}
		
		// generate string to be hashed and generate hash
		$hash = $xtraText . md5($xtraText . $password);
		
		// return hash
		return $hash;
	}
	
	/**
	 * This function verify if a password hash corresponds to a provided
	 * password. It uses the function calculatePasswordHash, and passwordHash
	 * must accomplish that function (that is, it is generated by this function).
	 * Function verifies if password generates same passwordHash.  
	 * 
	 * @param string $password
	 * @param string $passwordHash
	 * @return boolean
	 */
	function validatePassword ($password, $passwordHash) {
		
		$validated = false;
		
		// get the extra text stored along the password hash
		$xtraText = substr($passwordHash, 0, 8);
		
		// generate password hash using password and xtraText  
		$passwordHashForProvidedPassword = calculatePasswordHash($password, $xtraText);
		
		// compare both hashes
		if ($passwordHashForProvidedPassword == $passwordHash) {
			$validated = true;
		}
		else {
			$validated = false;
		}
		
		// return validation
		return $validated;
	}
	
?>